package com.grape.utils;

import com.grape.constants.Constants;
import com.grape.error.BusinessException;
import com.grape.property.FileProperty;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


/**
 * 类描述： 文件工具类
 *
 * @author  putao
 * @email   2628279194@qq.com
 */
@Component(value = "filesUtils")
@AllArgsConstructor
public class FilesUtils implements UploadUtils {

    private static final Logger logger = LoggerFactory.getLogger(FilesUtils.class);

    private final FileProperty fileProperty;

    /**
     * 文件上传
     * @param file          文件对象
     * @param is            文件输入流
     * @return              上传后路径
     * @throws IOException  异常
     */
    public String upload(MultipartFile file, InputStream is) throws IOException {
        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        String result = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        // 防止覆盖文件，文件名是加上当前时间戳
        String fileName = originalFilename.substring(0, originalFilename.lastIndexOf("." + result));
        // 主路径
        String filepath = fileProperty.getUploadLinux();
        File upload = new File(filepath + fileName + "." + result);
        String resultUrl = Constants.HTTP + fileProperty.getIp() + Constants.IMG_NAME + Constants.SLASH + fileName + "." + result;
        logger.info("文件地址" + resultUrl);
        logger.info("路径地址" + upload.getAbsolutePath());
        //判断文件的父类文件不为null ，并且不是文件夹
        if (upload.getParentFile() != null && !upload.getParentFile().isDirectory()) {
            upload.getParentFile().mkdirs();
            // 创建文件
            upload.createNewFile();
        }
        // 若目标文件夹不存在，则创建
        if (!upload.exists()) {
            upload.createNewFile();
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(upload);
            byte[] buffer = new byte[1024 * 1024];
            int byteRead = 0;
            while ((byteRead = is.read(buffer)) != -1) {
                fos.write(buffer, 0, byteRead);
                fos.flush();
            }
        } catch (Exception e) {
            logger.warn("文件上传失败{}", e.getMessage());
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (Exception e) {
            }
        }
        File file1 = new File(upload.getAbsolutePath());
        logger.info("存在" + file1.exists());
        return resultUrl;
    }


    /**
     * 文件上传
     * @param file              文件对象
     * @return                  上传后路径
     * @throws IOException      异常
     */
    public String upload(MultipartFile file) throws IOException {
        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        String result = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        // 防止覆盖文件，文件名是加上当前时间戳
        String fileName = originalFilename.substring(0, originalFilename.lastIndexOf("." + result));
        // 主路径
        String filepath = fileProperty.getUploadLinux();
        File upload = new File(filepath + fileName + "." + result);
        String resultUrl = Constants.HTTP + fileProperty.getIp() + Constants.IMG_NAME + Constants.SLASH + fileName + "." + result;
        logger.info("文件地址" + resultUrl);
        // 判断文件的父类文件不为null ，并且不是文件夹
        if (upload.getParentFile() != null && !upload.getParentFile().isDirectory()) {
            upload.getParentFile().mkdirs();
            // 创建文件
            upload.createNewFile();
        }
        // 若目标文件夹不存在，则创建
        if (!upload.exists()) {
            upload.createNewFile();
        }
        FileOutputStream fos = null;
        InputStream inputStream = file.getInputStream();
        try {
            fos = new FileOutputStream(upload);
            byte[] buffer = new byte[1024 * 1024];
            int byteRead = 0;
            while (true) {
                if ((byteRead = inputStream.read(buffer)) == -1) break;
                fos.write(buffer, 0, byteRead);
                fos.flush();
            }
        } catch (Exception e) {
            logger.warn("文件上传失败{}", e.getMessage());
            throw new BusinessException(e.getMessage());
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                throw new BusinessException(e.getMessage());
            }
        }
        return resultUrl;
    }
}
